package org.example.mq.mqserver.core;
/*
  交换机
 */

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;


@Data
public class Exchange {
    @TableId(type = IdType.INPUT)
    //交换机名, 并且一个BrokerServer中只能有一个
    private String name;

    //交换机类型    DIRECT  FANOUT TOPIC
    private ExchangeType type = ExchangeType.DIRECT;

    //交换机是否要持久化  有些交换机比较重要就需要持久化
    private boolean durable;

    //交换机是否自动删除
    private boolean autoDelete;

    //交换机额外参数选项
    private Map<String,Object> arguments = new HashMap<>();

    //将arguments转换成json字符串 方便存储到数据库
    public String getArguments(){
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(arguments);
        } catch (Exception e) {
            e.printStackTrace();
            return "{}";
        }
    }

    //设置数据库返回的arguments json转换成map
    public void setArguments(String arguments){
        if(arguments == null || arguments.equals("null")){
            this.arguments = null;
            return;
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            this.arguments = mapper.readValue(arguments, new TypeReference<Map<String,Object>>(){});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Exchange(String name, ExchangeType type, boolean durable, boolean autoDelete) {
        this.name = name;
        this.type = type;
        this.durable = durable;
        this.autoDelete = autoDelete;
    }

    public Exchange() {
    }

    public Object getArgument(String key){
        return arguments.get(key);
    }

    public void setArgument(String key, Object value) {
        arguments.put(key, value);
    }

    public void setArguments(Map<String, Object> arguments) {
        this.arguments = arguments;
    }
}
